﻿using Himp.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.DistributedLocking;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace Himp.Outpatient
{
    /// <summary>
    /// 门诊发票
    /// </summary>
    public class OtpInvoService : OutpatientAppService, IOtpInvoService
    {
        private readonly IRepository<OtpInvo, Guid> _otpInvoRepository;
        private readonly IAbpDistributedLock _distributedLock;

        public OtpInvoService(IRepository<OtpInvo, Guid> otpInvoRepository
            , IAbpDistributedLock distributedLock)
        {
            _otpInvoRepository = otpInvoRepository;
            _distributedLock = distributedLock;
        }

        public async Task<OtpInvoDto> GetAsync()
        {
            var iQuery = await _otpInvoRepository.GetQueryableAsync();
            iQuery = iQuery.Where(i => true);
            var otpInvo = iQuery.FirstOrDefault();
            var itemDto = ObjectMapper.Map<OtpInvo, OtpInvoDto>(otpInvo);

            return itemDto;
        }

        public async Task<OtpInvoDto> PostAsync()
        {
            var iQuery = await _otpInvoRepository.GetQueryableAsync();
            iQuery = iQuery.Where(i => true);
            var acquireKey = "invono:" + CurrentUser.Id;
            await using (var handle = await _distributedLock.TryAcquireAsync(acquireKey))
            {
                if (handle != null)
                {
                    var otpInvo = iQuery.FirstOrDefault();
                    otpInvo.CurnIndex++;
                    otpInvo.CurnInvono = string.Format(otpInvo.InvnoTemplate, otpInvo.CurnIndex);
                    otpInvo = await _otpInvoRepository.UpdateAsync(otpInvo);
                    var itemDto = ObjectMapper.Map<OtpInvo, OtpInvoDto>(otpInvo);

                    return itemDto;
                }
            }

            throw new UserFriendlyException("获取发票号失败！");
        }
    }
}
